package com.jt.service.impl;

import com.jt.dao.MenuMapper;
import com.jt.pojo.Menu;
import com.jt.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    //@Autowired
    //private RedisTemplate redisTemplate;

    //系统底层会基于redisTemplate这个名字找到RedisTemplate对象,
    //然后传给ValueOperations接口对应的实现类中的构造方法.
    @SuppressWarnings("all")//去警告
    @Resource(name="redisTemplate")
    private ValueOperations valueOperations;

    @Override
    public Menu selectById(Long id) {
        //1.从redis获取id(key)对应的数据,有则直接返回
        //ValueOperations valueOperations = redisTemplate.opsForValue();
        Menu menu = (Menu)valueOperations.get(String.valueOf(id));
        if(menu!=null)return menu;
        //2.从mysql查询数据,并将数据存储到redis中
        menu = menuMapper.selectById(id);
        valueOperations.set(String.valueOf(id), menu,100);
        return menu;
    }

    @Override
    public Menu insertMenu(Menu menu) {
        System.out.println("insert.before.menu:"+menu);
        //1.向mysql写数据
        menuMapper.insert(menu);
        System.out.println("insert.after.menu:"+menu);
        //2.向redis写数据
        //ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(String.valueOf(menu.getId()), menu);
        return menu;
    }

    @Override
    public Menu updateMenu(Menu menu) {
        System.out.println("update.before.menu:"+menu);
        //1.向mysql写数据
        menuMapper.updateById(menu);
        System.out.println("update.after.menu:"+menu);
        //2.向redis写数据
        //ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(String.valueOf(menu.getId()), menu);
        return menu;
    }
}
